from random import randint

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from libs.captcha.captcha import captcha  # 图片验证码库
from django_redis import get_redis_connection

from libs.yuntongxun.sms import CCP

'''
前端：拼接一个url, 赋值给img,之后img发送请求
url= http://ip:port/image_codes/uuid/
后端：
    请求: 接收url中的uuid
    业务逻辑:生成图片和图片二进制，通过redis保存信息
    响应：发送图片二进制码
'''


# Create your views here.
class ImageCodeView(View):
    def get(self, request, uuid):
        text, img = captcha.generate_captcha()
        redis = get_redis_connection('code')
        redis.setex(uuid, 3600, text)  # 名字，过期秒数，保留内容
        return HttpResponse(img, content_type='image/jpeg')


class SMSCodeView(View):
    def get(self, request, mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 判断验证码
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        redis_conn = get_redis_connection('code')
        redis_image_code = redis_conn.get(uuid)
        if redis_image_code is None:
            return JsonResponse({'code': 400, 'errmsg': '图片验证码过期'})
        elif image_code.lower() != redis_image_code.decode().lower():
            return JsonResponse({'code': 400, 'errmsg': '图片验证码不正确'})
        # 提取发送短信标记
        send_flag = redis_conn.get('send_flag%s' % mobile)
        if send_flag is not None:
            return JsonResponse({'code': 400, 'errmsg': '发送过于频繁'})
        # 生成随机数 以作为手机号验证码
        sms_code = '%06d' % randint(0, 999999)

        # 创建管道发送请求
        pl = redis_conn.pipeline()
        pl.setex(mobile, 600, sms_code)
        # 设置短信标记防止重复发送(key,time,value)
        pl.setex('send_flag%s' % mobile, 60, 1)
        pl.execute()
        # 发送短信
        # CCP().send_template_sms('17633363360', [sms_code, 10], 1)
        # 使用多线程
        from celery_tasks.sms.tasks import celery_send_sms_code
        # celery_send_sms_code.delay('17633363360', sms_code)
        celery_send_sms_code.delay(mobile, sms_code)
        return JsonResponse({'code': 0, 'errmsg': 'ok'})



